﻿using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Utility
{
    /// <summary>
    /// google translate翻译者类[非API，URL访问Google的方式]
    /// ZhangQingFeng    2012-7-27    add
    /// </summary>
    public class GoogleTranslator
    {
        //private string UrlTemplate = "http://translate.google.com.hk/?langpair={0}&text={1}";    //google翻译URL模板:GET方式请求
        private string UrlTemplate = "http://translate.google.cn/";                            //google翻译URL模板:POST方式请求

        #region 常用语言编码

        private string AutoDetectLanguage = "auto"; //google自动判断来源语系

        #endregion 常用语言编码

        /// <summary>
        /// 翻译文本[自动检测源语言类型]
        /// ZhangQingFeng    2012-7-27    add
        /// </summary>
        /// <param name="sourceText">源文本</param>
        /// <param name="targetLanguageCode">目标语言类型代码，如：en、zh-CN、zh-TW、ru等</param>
        /// <returns>翻译结果</returns>
        public string Translate(string sourceText, string targetLanguageCode)
        {
            return Translate(sourceText, AutoDetectLanguage, targetLanguageCode);
        }

        /// <summary>
        /// 翻译文本
        /// ZhangQingFeng    2012-7-27    add
        /// </summary>
        /// <param name="sourceText">源文本</param>
        /// <param name="sourceLanguageCode">源语言类型代码，如：en、zh-CN、zh-TW、ru等</param>
        /// <param name="targetLanguageCode">目标语言类型代码，如：en、zh-CN、zh-TW、ru等</param>
        /// <returns>翻译结果</returns>
        public string Translate(string sourceText, string sourceLanguageCode, string targetLanguageCode)
        {
            if (string.IsNullOrEmpty(sourceText) || Regex.IsMatch(sourceText, @"^\s*$"))
            {
                return sourceText;
            }

            string strReturn = string.Empty;

            #region POST方式实现，无长度限制

            //string url = UrlTemplate;

            ////组织请求的数据
            //string postData = string.Format("langpair={0}&text={1}", HttpUtility.UrlEncode(sourceLanguageCode + "|" + targetLanguageCode), HttpUtility.UrlEncode(sourceText));
            //byte[] bytes = Encoding.UTF8.GetBytes(postData);

            //WebClient client = new WebClient();
            //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            //client.Headers.Add("ContentLength", postData.Length.ToString());
            //byte[] responseData = client.UploadData(url, "POST", bytes);
            //string encode_page = "";
            //if (targetLanguageCode == "ms")
            //{
            //    encode_page = "gb2312";
            //}
            //else if (targetLanguageCode == "zh-TW")
            //{
            //    strReturn = Microsoft.VisualBasic.Strings.StrConv(sourceText, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0);
            //    return strReturn;
            //}
            //else if (targetLanguageCode == "en")
            //{
            //    encode_page = "gb2312";
            //}

            //string strResult = Encoding.GetEncoding(encode_page).GetString(responseData);    //响应结果

            #endregion POST方式实现，无长度限制

            #region GET方式实现，有长度限制

            if (targetLanguageCode == "zh-TW")
            {
                strReturn = Microsoft.VisualBasic.Strings.StrConv(sourceText, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0);
                return strReturn;
            }

            string urlTpl = "http://fanyi.youdao.com/openapi.do?keyfrom=zhuyelionet&key=1398498338&type=data&doctype=json&version=1.1&q={0}";
            string url = string.Format(urlTpl, HttpUtility.UrlEncode(sourceText));
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;
            string strResult = wc.DownloadString(url);                //响应结果

            Dictionary<string, object> dict = JSONHelper.Instance.JavaScriptDeserializationMachion<Dictionary<string, object>>(strResult);
            strResult = "";
            if (int.Parse(dict["errorCode"].ToString()) == 0)
            {
                strResult = dict["translation"].ToString();
                strReturn = "";
                MatchCollection coll = Regex.Matches(strResult, "\"(.*)\"");
                foreach (Match m in coll)
                {
                    strReturn += m.Groups[1] + ",";
                }
                strReturn = strReturn.TrimEnd(',');
            }

            #endregion GET方式实现，有长度限制

            //XmlDocument xml = new XmlDocument();
            //xml.LoadXml(strResult);
            //XmlNode el = xml.SelectSingleNode(@"//result_box/span");

            //使用的正则表达式：    \s+id="?result_box"?\s+[^>]*>(.+)</span>\s*</div>\s*</div>\s*<div id=spell-place-holder\s+
            // string strReg = @"\s+id=""?result_box""?\s+[^>]*>(.+)</span>\s*</div>\s*</div>\s*<div id=spell-place-holder\s+";
            //string strReg = @"\s+id=""?result_box""?\s+[^>]*><span?\s+[^>]*>(.+)</span>";
            //Match match = Regex.Match(strResult, strReg, RegexOptions.IgnoreCase | RegexOptions.Singleline);

            //if (match.Success)
            //{
            //    strReturn = match.Groups[1].Value;
            //    strReturn = strReturn.Substring(0, strReturn.IndexOf('<'));
            //    ////<br/>替换为换行，如为HTML翻译选项则可去除下行代码
            //    //strReturn = Regex.Replace(strReturn, @"<br\s*/?>", "\n", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            //    //strReturn = Regex.Replace(strReturn, @"<[^>]*>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            //    //strReturn = HttpUtility.HtmlDecode(strReturn);
            //}
            return strReturn;
        }
    }
}